package com.qiaoba.file.ftp.config;

import cn.hutool.extra.spring.SpringUtil;
import com.qiaoba.common.base.exception.ServiceException;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PreDestroy;
import java.io.IOException;

/**
 * FTP文件存储 配置
 *
 * @author ailanyin
 * @date 2023-09-26 14:39:46
 */
@Configuration
@ComponentScan("com.qiaoba.file.ftp")
public class FtpConfig {

    @Value("${ftp.ip}")
    private String ip;
    @Value("${ftp.port}")
    private Integer port;
    @Value("${ftp.username}")
    private String username;
    @Value("${ftp.password}")
    private String password;

    @Bean
    public FTPClient ftpClient() {
        try {
            FTPClient ftpClient = new FTPClient();
            ftpClient.connect(ip, port);
            boolean result = ftpClient.login(username, password);
            if (!result) {
                throw new ServiceException("FTP服务器连接失败, 请检查账号密码！");
            }
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            return ftpClient;
        } catch (IOException e) {
            throw new ServiceException("FTP服务器连接失败, 错误信息: " + e.getMessage());
        }
    }


    @PreDestroy
    public void close() {
        try {
            SpringUtil.getBean(FTPClient.class).disconnect();
        } catch (IOException e) {

        }
    }

}
